package com.example.sys.org.quartz;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import com.example.core.utils.StringUtils;
import com.example.sys.job.annotation.JobScope;
import com.example.sys.org.po.SysUser;
import com.example.sys.org.service.SysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/***
 *
 * 用户年龄更新的定时任务
 */
@JobScope(name = "计算用户的年龄", cron = "*/30 * * * * ?", desc = "计算用户的年龄")
@Service
public class SysUserAgeUpdateJob implements Job {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysUserService sysUserService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        List<SysUser> sysUsers = sysUserService.getUserInfoNeedCalculate();
        for (SysUser sysUser : sysUsers) {
            if (StringUtils.isNotEmpty(sysUser.getCode())) {
                if (sysUser.getBirthDate() == null) {
                    DateTime birthDate = IdcardUtil.getBirthDate(sysUser.getCode());
                    sysUser.setBirthDate(birthDate);
                }
                if (StringUtils.isNotEmpty(sysUser.getCode())){
                    int age = IdcardUtil.getAgeByIdCard(sysUser.getCode());
                    sysUser.setAge(age);
                    sysUserService.saveOrUpdate(sysUser);
                }
            }
        }
    }
}
